//
//  ActivityViewController.m
//  豆瓣
//
//  Created by dllo on 15/12/7.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ActivityViewController.h"
#import "ActivityTableViewCell.h"
#import "AppTools.h"
#import "ActivityDetailViewController.h"
#import "AFNetworking.h"
#import "DataBaseSingleton.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"


@interface ActivityViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉

@end

@implementation ActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    self.allArray = [NSMutableArray array];
    

//    [self afnGetRequest];
    
    self.navigationItem.title = @"活动";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.myTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:_myTableView];
    [_myTableView release];
    
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];
    
    NSString *url_string = [NSString stringWithFormat:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"];
    
    NSMutableArray *array = [[DataBaseSingleton shareDataBase] selectActivityDetail];
    self.allArray = [NSMutableArray arrayWithArray:array];
    
    [AppTools getDataWithAFNURL:url_string block:^(id result) {
        
        
        self.allArray = [NSMutableArray array];
        
        NSMutableDictionary *dic = result;
        NSMutableArray *array = [dic objectForKey:@"events"];
        
        for (NSDictionary *dic in array) {
            ActivityList *activityList = [[ActivityList alloc] init];
            [activityList setValuesForKeysWithDictionary:dic];
            //            NSLog(@"%@", model);
            [self.allArray addObject:activityList];
            [activityList release];
        }
        
        [self.myTableView reloadData];
        
    } errorBlock:^(NSError *error) {
        
        
        
    }];
    
    


    
}

//- (void)initListData{
//            [self afnGetRequest];
//
//}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block ActivityViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc afnGetRequest:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block ActivityViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc afnGetRequest:vc.nextPage];//请求数据
        
    }];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    ActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[ActivityTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    ActivityList *activity = [self.allArray objectAtIndex:indexPath.row];
    cell.activity = activity;
    
//    cell.textLabel.text = @"大水杯";
    
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.allArray.count;
}

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return self.allArray.count;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 186;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ActivityDetailViewController *activityDetailVC = [[ActivityDetailViewController alloc] init];
    activityDetailVC.activityList = [self.allArray objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:activityDetailVC animated:YES];
    [activityDetailVC release];
}


-(void)afnGetRequest:(NSInteger)nextCursor
{
    

    
    //检查网络状态管理者 是单例
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"网络状态 = %ld", status);
    }];
    

    
    NSString *url_string = [NSString stringWithFormat:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"];
    
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    //请求管理者 所有的网络请求,均有manager发起
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        [netWorkManager stopMonitoring];
        NSLog(@"=====%d", [NSThread isMainThread]);
//        // 回到主线程
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            
//            
//        });
//                NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        self.allArray = [NSMutableArray array];
        
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *array = [dic objectForKey:@"events"];
        
        for (NSDictionary *dic in array) {
            ActivityList *activityList = [[ActivityList alloc] init];
            [activityList setValuesForKeysWithDictionary:dic];
            //            NSLog(@"%@", model);
            [self.allArray addObject:activityList];
            [activityList release];
        }
        
        [self.myTableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
